package com.ja.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2019/6/4.
 */
public class CorsFilter implements Filter {
    private boolean isCors = false;
    private static final String REQUEST_METHOD = "POST, GET, OPTIONS, DELETE";
    private static final String REQUEST_ORIGIN = "*";
    private static final String REQUEST_MAX_AGE = "0";
    private static final String REQUEST_HEADER = "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token";
    private static final String REQUEST_CREDENTIAL = "true";
    private static final String REQUEST_XDOMAIN = "1";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isCorssStr = filterConfig.getInitParameter("IsCross");
        isCors = isCorssStr.equals("true") ? true : false;
        System.out.println(isCorssStr);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (isCors) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            System.out.println("拦截请求========>" + httpServletRequest.getServletPath());
            httpServletResponse.setHeader("Access-Control-Allow-Origin", REQUEST_ORIGIN);
            httpServletResponse.setHeader("Access-Control-Allow-Methods", REQUEST_METHOD);
            httpServletResponse.setHeader("Access-Control-Max-Age", REQUEST_MAX_AGE);
            httpServletResponse.setHeader("Access-Control-Allow-Headers", REQUEST_HEADER);
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", REQUEST_CREDENTIAL);
            httpServletResponse.setHeader("XDomainRequestAllowed", REQUEST_XDOMAIN);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        isCors = false;
    }
}
